<?php

// Init owncloud

JLoader::register("PCompanyModelThirdAccounts", OC::$SERVERROOT."/apps/company/lib/thirdaccounts.php");
JLoader::register("PResumesHelper", OC::$SERVERROOT."/apps/resumes/lib/helper.php");
JLoader::register("PJobpositionHelper", OC::$SERVERROOT."/apps/jobposition/lib/helper.php");


OCP\JSON::callCheck();
if(!OC_User::isLoggedIn()) {
   echo '您需要先登录';
   exit;
} else {
   if (PFactory::isJobseekerUser()) {
      echo "您无权访问该资源！";
      exit;
   }
}

$type = JRequest::getString('type', 0);
$job_id = JRequest::getInt('job_id',0);
$addjob = JRequest::getInt('addjob',0);
$term_id = JRequest::getInt('term_id',0);
$pageno = JRequest::getInt('pageno',0);
$resumecode = JRequest::getString('resumecode','');
$resumecodes = json_decode($resumecode, true);
$jobids = JRequest::getVar('jobids',array(),'','array');

if ( !empty($job_id) && !PCompanyHelper::checkJobManagerPermissions($job_id) ) {
   echo "您无权访问该资源！";
   exit;
}

if ( !empty($jobids) && !PCompanyHelper::checkJobsManagerPermissions($jobids) ) {
   echo "您无权访问该资源！";
   exit;
}

//FIXME: syncaction should be a list: syncinfo, fetchjobs, fetchseekers, etc by default when we support all of them 
$syncaction = JRequest::getString("syncaction", 'fetchjobs');

$captcha = ''; 
$model = new PCompanyModelThirdAccounts();

switch ($syncaction) {
   case 'addjob':
   case 'editjob':
      $errormsg = '';
      // Check jobposition has all the data we need to push to 51job/zhilian etc.
      $is_valid = PJobpositionHelper::checkJobpositionDetail($job_id,$errormsg);
      if ($is_valid === false) {
         echo $errormsg;;
         exit;
      }
      
      if ($addjob) {
         $ids = PJobpositionHelper::getGroupsJobsId($job_id);
         $jobid_arr = !empty($ids) ? JArrayHelper::getColumn($ids, 'id') : (empty($job_id) ? array() : array($job_id));
      } else {
         $jobid_arr = empty($job_id) ? array() : array($job_id);
      }
      $param = empty($jobid_arr) ? array() : array('jobids'=>$jobid_arr);
      break;
   case 'searchresumes':
      $param = array('tid'=>$term_id, 'pageno'=>$pageno);
      break;
   case 'saveresumes':
      $param = array('resumecodes'=>$resumecodes);
      break;
   case 'renewjobs':
      $param = array('jobids'=>$jobids);
      break;
   default:
      $param = array();
      break;
}

$sync_info = $model->trySync($type, explode(",", $syncaction), $param, $captcha);
if($sync_info === false) {
   // something happens, we don't need to continue
   echo $model->getError();
   exit;
}

$thirdtools_account_info = !empty($sync_info['login']) ? json_decode($sync_info['login'],true) : null;
$account_cookie = !empty($sync_info['cookie']) ? json_decode($sync_info['cookie'],true) : null;

$thirdaccount = empty($thirdtools_account_info[$type]) ? null : $thirdtools_account_info[$type];
$cookie = empty($account_cookie[$type]) ? null : $account_cookie[$type]; 

$username = isset($thirdaccount['username']) ? $thirdaccount['username'] : '';
$membername = isset($thirdaccount['membername']) ? $thirdaccount['membername'] : '';
$password = isset($thirdaccount['password']) ? $thirdaccount['password'] : '';

$msg = "";

if($syncaction == "autofetchjobs"){
   $msg = '同步';
}else if($syncaction == "autorenewjobs"){
   $msg = '刷新';
}

$button = "开始同步";

if($syncaction == "autofetchjobs" || $syncaction == "autorenewjobs"){
   $button = "确定";
}else if($syncaction == "searchresumes"){
   $button = '开始搜索';
}

?>

<?php if ($type == '51job'): ?>
<!-- Modal 51job -->
   <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
      <ul class="nav nav-tabs" id="myTab">
         <li class="active"><a href="#home_51" data-toggle="tab">前程无忧</a></li>
      </ul>
   </div>
   <div class="modal-body">
      <div class="tab-content">
         <div class="tab-pane active" id="home_51">
            <div class="formtip medium"><?php if(!empty($msg)){echo "启用自动".$msg."，需保存您在前程无忧的账号信息";}else{echo "请输入您在前程无忧的账号信息，仅用于数据同步";}?></div>
            <form id="sync_form_51job" action="<?php echo OC_Helper::linkToRoute("company_startsyncaccount"); ?>" method="post">
            <input type="hidden" name="type" value="51job">
            <?php if(!empty($job_id)): ?>
            <input type="hidden" name="job_id" value="<?=$job_id?>">
            <?php endif; ?>
            <?php if(!empty($jobids)): ?>
            <input type="hidden" name="jobids" value="<?=(implode(',',$jobids))?>">
            <?php endif; ?>
            <input type="hidden" name="syncaction" value="<?=$syncaction?>">
            <input type="hidden" name="resumecode" value='<?=$resumecode?>'>
            <input type="hidden" name="term_id" value="<?=$term_id?>">
            <input type="hidden" name="pageno" value="<?=$pageno?>">

            <div class="form-horizontal accountsetform">
              <div class="control-group">
                <label class="control-label key">会员名:</label>
                <div class="controls">
                   <input type="text" name="account_membername" class="required" value="<?=$membername?>">
                </div>
              </div>
              <div class="control-group">
                <label class="control-label key">用户名:</label>
                <div class="controls">
                  <input type="text" name="account_username" class="required" value="<?=$username?>">
                </div>
              </div>
              <div class="control-group" style="margin-bottom:5px;">
                <label class="control-label key">密码:</label>
                <div class="controls">
                  <?php if(!empty($password)): ?>
                  <input type="password" name="account_password" maxlength="12" data-minlength="6" data-exist="1" value="" autocomplete="off" placeholder="●●●●●●●●">
                  <?php else: ?>
                  <input type="password" name="account_password" maxlength="12" minlength="6" class="required" autocomplete="off" value=''>
                  <?php endif; ?>
                </div>
              </div>
              <div id="captcha_div" class="control-group" style="margin-bottom:5px;margin-top:12px;display:<?php echo !empty($captcha) ? 'block' : 'none';?>;">
                <label class="control-label key">验证码:</label>
                <div class="controls clearfix">
                  <input id="captcha_input" type="text" name="captcha" class="input-small pull-left required" <?php echo empty($captcha) ? 'disabled="disabled"' : '' ?>>
                  <label class="pull-left" style="margin:3px 0 0 4px;">
                  <img id="51_captcha" class='captcha' src="data:image/png;base64,<?=$captcha?>" />
                  </label>
                  <label class="error" for="captcha" generated="true" style="display:none;"></label>
                </div>
              </div>
              <div class="control-group">
                <div class="controls">
                  <?php if(empty($password)): ?>
                  <label class="checkbox medium gray">
                    <input type="checkbox" name="rememberme" value="1" checked="checked" <?php echo ($syncaction == 'autofetchjobs' || $syncaction == 'autorenewjobs')? 'disabled' : ''; ?>> 记住密码<em style="color:#999999;">（以后不需要再输入账号密码）</em>
                    <?php if($syncaction == 'autofetchjobs' || $syncaction == 'autorenewjobs'): ?>
                    <input type="hidden" name="rememberme" value="1">
                    <?php endif; ?>
                  </label>
                  <?php endif; ?>
                  <?php if($syncaction == 'fetchjobs'): ?>
                  <label class="checkbox medium gray">
                    <input type="checkbox" name="addfetchresumes"/> 同时导入公司人才夹简历
                  </label>
                  <?php endif; ?>
                  <input type="hidden" name="requesttoken" value="<?php echo PSession::getFormToken();?>" id="requesttoken">
                  <input type="submit" class="ppp_bluebtn btn medium" value="<?=$button ?>" style="margin-top:5px;"/>
                  <span style="display:none" class="error systemerror medium"></span>
                </div>
              </div>
            </div>
            </form>
         </div>
      </div>
   </div>

<?php elseif ($type == 'zhilian'): ?>

<!-- Modal zhilian -->
   <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
      <ul class="nav nav-tabs" id="myTab">
         <li class="active"><a href="#home_zhilian" data-toggle="tab">智联招聘</a></li>
      </ul>
   </div>
   <div class="modal-body">
      <div class="tab-content">
         <div class="tab-pane active" id="home_zhilian">
            <div class="formtip medium"><?php if(!empty($msg)){echo "启用自动".$msg."，需保存您在智联招聘的账号信息";}else{echo "请输入您在智联招聘的账号信息，仅用于数据同步";}?></div>
            <form id="sync_form_zhilian" action="<?php echo OC_Helper::linkToRoute("company_startsyncaccount"); ?>" method="post">
            <input type="hidden" name="type" value="zhilian">
            <?php if(!empty($job_id)): ?>
            <input type="hidden" name="job_id" value="<?=$job_id?>">
            <?php endif; ?>
            <?php if(!empty($jobids)): ?>
            <input type="hidden" name="jobids" value="<?=(implode(',',$jobids))?>">
            <?php endif; ?>
            <input type="hidden" name="syncaction" value="<?=$syncaction?>">
            <input type="hidden" name="resumecode" value='<?=$resumecode?>'>
            <input type="hidden" name="term_id" value="<?=$term_id?>">
            <input type="hidden" name="pageno" value="<?=$pageno?>">

            <div class="form-horizontal accountsetform">
              <div class="control-group">
                <label class="control-label key">用户名:</label>
                <div class="controls">
                  <input type="text" name="account_username" class="required" value="<?=$username?>">
                </div>
              </div>
              <div class="control-group" id="zhilian_password_div">
                <label class="control-label key">密码:</label>
                <div class="controls">
                  <?php if(!empty($password)): ?>
                  <input type="password" name="account_password" maxlength="40" data-minlength="8" data-exist="1" value="" autocomplete="off" placeholder="●●●●●●●●">
                  <?php else: ?>
                  <input type="password" name="account_password" maxlength="40" minlength="8" class="required" autocomplete="off" value="">
                  <?php endif; ?>
                </div>
              </div>
              <div class="control-group" style="margin-bottom:5px;">
                <label class="control-label key">验证码:</label>
                <div class="controls clearfix">
                  <input type="text" name="captcha" class="input-small required pull-left">
                  <label class="pull-left" style="margin-bottom:0px;">
                    <img id="zhilian_captcha" class='captcha' src="data:image/png;base64,<?=$captcha?>" style="padding-left:5px; padding-top:2px;" />
                  </label>
                  <label class="error" for="captcha" generated="true" style="display:none;"></label>
                </div>
              </div>
              <div class="control-group" style="margin-top:<?=$syncaction == 'fetchjobs' ? '-10' : '5';?>px;">
                <div class="controls">
                  <?php if(empty($password)): ?>
                  <label class="checkbox medium gray">
                    <input type="checkbox" name="rememberme" value="1" checked="checked" <?php echo ($syncaction == 'autofetchjobs' || $syncaction == 'autorenewjobs')? 'disabled' : ''; ?>> 记住密码<em style="color:#999999;">（以后不需要再输入账号密码）</em>
                    <?php if($syncaction == 'autofetchjobs' || $syncaction == 'autorenewjobs'): ?>
                    <input type="hidden" name="rememberme" value="1">
                    <?php endif; ?>
                  </label>
                  <?php endif; ?>
                  <?php if($syncaction == 'fetchjobs'): ?>
                  <label class="checkbox medium gray">
                    <input type="checkbox" name="addfetchresumes"/> 同时导入公司人才夹简历
                  </label>
                  <?php endif; ?>
                  <input type="hidden" name="requesttoken" value="<?php echo PSession::getFormToken();?>" id="requesttoken">
                  <input type="submit" class="ppp_bluebtn btn medium" value="<?=$button ?>" style="margin-top:5px;"/>
                  <span style="display:none" class="error systemerror medium"></span>
                </div>
              </div>
            </div>
            </form>
         </div>
      </div>
   </div>

<?php elseif ($type == 'lagou'): ?>

<!-- Modal lagou -->
   <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
      <ul class="nav nav-tabs" id="myTab">
         <li class="active"><a href="#home_lagou" data-toggle="tab">拉勾</a></li>
      </ul>
   </div>
   <div class="modal-body">
      <div class="tab-content">
         <div class="tab-pane active" id="home_lagou">
            <div class="formtip medium">枇杷派与拉勾为深度合作伙伴，绑定账号即可使用所有服务</div>
            <form id="sync_form_lagou" action="<?php echo OC_Helper::linkToRoute("company_startsyncaccount"); ?>" method="post">
            <input type="hidden" name="type" value="lagou">
            <?php if(!empty($job_id)): ?>
            <input type="hidden" name="job_id" value="<?=$job_id?>">
            <?php endif; ?>
            <?php if(!empty($jobids)): ?>
            <input type="hidden" name="jobids" value="<?=(implode(',',$jobids))?>">
            <?php endif; ?>
            <input type="hidden" name="syncaction" value="<?=$syncaction?>">         
            <input type="hidden" name="resumecode" value='<?=$resumecode?>'>
            <input type="hidden" name="term_id" value="<?=$term_id?>">
            <input type="hidden" name="pageno" value="<?=$pageno?>">

            <div class="form-horizontal accountsetform">
              <div class="control-group">
                <label class="control-label key">邮箱地址:</label>
                <div class="controls">
                  <input type="text" name="account_username" class="required" value="<?=$username?>">
                </div>
              </div>
              <div class="control-group" id="jiancai_password_div">
                <label class="control-label key">密码:</label>
                <div class="controls">
                  <?php if(!empty($password)): ?>
                  <input type="password" name="account_password" maxlength="25" data-minlength="6" data-exist="1" value="" autocomplete="off" placeholder="●●●●●●●●">
                  <?php else: ?>
                  <input type="password" name="account_password" maxlength="25" minlength="6" class="required" autocomplete="off" value="">
                  <?php endif; ?>
                </div>
              </div>
              <div class="control-group" style="margin-top:-5px;">
                <div class="controls">
                  <?php if(empty($password)): ?>
                  <label class="checkbox medium gray">
                    <input type="checkbox" name="rememberme" value="1" checked="checked" disabled> 记住密码<em style="color:#999999;">（以后不需要再输入账号密码）</em>
                    <input type="hidden" name="rememberme" value="1">
                  </label>
                  <?php endif; ?>
                  <input type="hidden" name="requesttoken" value="<?php echo PSession::getFormToken();?>" id="requesttoken">
                  <input type="submit" class="ppp_bluebtn btn medium" value="开始同步" style="margin-top:5px;"/>
                  <em>还没有拉勾账号？<a href="http://www.lagou.com/register.html">立即注册</a></em>
                  <span style="display:none" class="error systemerror"></span>
                </div>
              </div>
            </div>
            </form>
         </div>
      </div>
   </div>

<?php elseif ($type == 'jiancai'): ?>

<!-- Modal jiancai -->
   <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
      <ul class="nav nav-tabs" id="myTab">
         <li class="active"><a href="#home_jiancai" data-toggle="tab">建筑英才</a></li>
      </ul>
   </div>
   <div class="modal-body">
      <div class="tab-content">
         <div class="tab-pane active" id="home_jiancai">
            <div class="formtip medium"><?php if(!empty($msg)){echo "启用自动".$msg."，需保存您在建筑英才的账号信息";}else{echo "请输入您在建筑英才的账号信息，仅用于数据同步";}?></div>
            <form id="sync_form_jiancai" action="<?php echo OC_Helper::linkToRoute("company_startsyncaccount"); ?>" method="post">
            <input type="hidden" name="type" value="jiancai">
            <?php if(!empty($job_id)): ?>
            <input type="hidden" name="job_id" value="<?=$job_id?>">
            <?php endif; ?>
            <?php if(!empty($jobids)): ?>
            <input type="hidden" name="jobids" value="<?=(implode(',',$jobids))?>">
            <?php endif; ?>
            <input type="hidden" name="syncaction" value="<?=$syncaction ?>">         
            <input type="hidden" name="resumecode" value='<?=$resumecode?>'>
            <input type="hidden" name="term_id" value="<?=$term_id?>">
            <input type="hidden" name="pageno" value="<?=$pageno?>">

            <div class="form-horizontal accountsetform">
              <div class="control-group">
                <label class="control-label key">用户名:</label>
                <div class="controls">
                  <input type="text" name="account_username" class="required" value="<?=$username?>">
                </div>
              </div>
              <div class="control-group" id="jiancai_password_div">
                <label class="control-label key">密码:</label>
                <div class="controls">
                  <?php if(!empty($password)): ?>
                  <input type="password" name="account_password" maxlength="25" data-minlength="6" data-exist="1" value="" autocomplete="off" placeholder="●●●●●●●●">
                  <?php else: ?>
                  <input type="password" name="account_password" maxlength="25" minlength="6" class="required" autocomplete="off" value="">
                  <?php endif; ?>
                </div>
              </div>
              <div id="captcha_div" class="control-group" style="margin-bottom:5px;display:<?php echo !empty($captcha) ? 'block' : 'none';?>;">
                <label class="control-label key">验证码:</label>
                <div class="controls clearfix">
                  <input type="text" name="captcha" class="input-small required pull-left" <?php echo empty($captcha) ? 'disabled="disabled"' : '' ?>>
                  <label class="pull-left">
                    <img id="jiancai_captcha" class='captcha' src="data:image/png;base64,<?=$captcha?>" style="padding-left:5px; padding-top:2px;" />
                  </label>
                  <label class="error" for="captcha" generated="true" style="display:none;"></label>
                </div>
              </div>
              <div class="control-group">
                <div class="controls">
                  <?php if(empty($password)): ?>
                  <label class="checkbox medium gray">
                    <input type="checkbox" name="rememberme" value="1" checked="checked" <?php echo ($syncaction == 'autofetchjobs' || $syncaction == 'autorenewjobs')? 'disabled' : ''; ?>> 记住密码<em style="color:#999999;">（以后不需要再输入账号密码）</em>
                    <?php if($syncaction == 'autofetchjobs' || $syncaction == 'autorenewjobs'): ?>
                    <input type="hidden" name="rememberme" value="1">
                    <?php endif; ?>
                  </label>
                  <?php endif; ?>
                  <?php if($syncaction == 'fetchjobs'): ?>
                  <label class="checkbox medium gray">
                    <input type="checkbox" name="addfetchresumes"/> 同时导入公司人才夹简历
                  </label>
                  <?php endif; ?>
                  <input type="hidden" name="requesttoken" value="<?php echo PSession::getFormToken();?>" id="requesttoken">
                  <input type="submit" class="ppp_bluebtn btn medium" value="<?=$button ?>" style="margin-top:5px;"/>
                  <span style="display:none" class="error systemerror medium"></span>
                </div>
              </div>
            </div>
            </form>
         </div>
      </div>
   </div>

<?php endif; ?>

<script type="text/javascript">
jQuery(document).ready(function($) {
   var validator_sync = {
      submitHandler: function(form) {
         var pobj = $("input[name='account_password']", form);
         var type = $("input[name='type']",form).val();
         var password = pobj.val();
         if(password.length > 0 && pobj.data('minlength') && password.length < pobj.data('minlength')) {
            $('.systemerror', form).jobUtil('showError', '请输入一个长度最少是 ' + pobj.data('minlength') + ' 的字符串');
            return;
         } else {
            $('.systemerror', form).hide();
         }

         var dialog = $(form).closest('div.accountsetdialog'); 
         $(form).ajaxSubmit({
            dataType: "json",
            beforeSubmit: function(data, form, options) {
               if(!showLoading(form))
                  return false;
            },
            success: function(data) {
               try {
                  if(data.error) {
                     $('.systemerror', form).jobUtil('showError', data.error);
                     if(data.data && data.data.captcha) {
                        $('.captcha', form).attr('src', 'data:image/png;base64,'+data.data.captcha); 
                        // For 51job we need more steps
                        $('#captcha_input', form).prop('disabled',false);
                        $('#captcha_div', form).show();
                     }
                  }else if(data.success){
                     if(data.success == 'task-add-to-background') {
                        $("#psysnotify").trigger("showtask");
                        dialog.data('submitted', true).find('button.close').trigger('click');

                        if($.isFunction(dialog.data('taskaddedcb')))
                           dialog.data('taskaddedcb')(true); 
                        if($('input[name=syncaction]',form).val() == "fetchjobs" || $('input[name=syncaction]',form).val() == "fetchjobs,fetchresumes"){
                           showNotifyDialog(dialog.data("autofetchon"),dialog.data("vid"), type);
                        }else if($('input[name=syncaction]',form).val() == "autofetchjobs" || $('input[name=syncaction]',form).val() == "autorenewjobs"){
                           $("#"+$('input[name=syncaction]',form).val()+"_result_"+type).children('.hdbtn').removeClass('hdbtn_notok').addClass('hdbtn hdbtn_ok');
                           $('#autofetchjobs_result_'+type+',#autorenewjobs_result_'+type).data('loginstatus',1);
                        }else{
                           OC.Notification.show(getSyncMessage($('input[name=syncaction]',form).val(), type), 5000);
                        }
                     }
                     else if(data.success == 'hidden-task-add-to-background') {
                        OC.Notification.show(getDataSyncMessage($('input[name=syncaction]').val(), $('input[name=type]').val()), 5000);
                        dialog.data('submitted', true).find('button.close').trigger('click');

                        if($.isFunction(dialog.data('taskaddedcb')))
                           dialog.data('taskaddedcb')(true); 
                     }
                     else {
                        var message = '<div style="text-align:center; padding: 30px 40px">' + 
                                      '<div class="success large">'+ (data.success == 'login-success' ? "登录成功！" : "登录状态良好！") + '<br><br>';
                        message += dialog.data('dataaction') ? '<div class="normal">'+getDataSyncMessage(dialog.data('dataaction'), $('input[name=type]').val()) + '</div>' : '';
                        message += '</div>';
                        dialog.find('.modal-body>div').html(message); 
   
                        setTimeout(function() {
                           dialog.data('submitted', true).find('button.close').trigger('click');
                           if($.isFunction(dialog.data('taskaddedcb')))
                              dialog.data('taskaddedcb')(); 
                        }, 2000);
                     }
                  }
               } catch(e) {
                  return false;
               }
            }
         });
      }
   };
   $("#sync_form_51job").validate(validator_sync);
   $("#sync_form_zhilian").validate(validator_sync);
   $("#sync_form_jiancai").validate(validator_sync);
   $("#sync_form_lagou").validate(validator_sync);

   $(document).on('focus','input[type="password"]',function(){
      $(this).prop('placeholder','');
   })
   $(document).on('focusout','input[type="password"]',function(){
      if($(this).data('exist')){
        $(this).prop('placeholder','●●●●●●●●');
      }else {
        $(this).prop('placeholder','');
      }
   })
   
})
</script>
